<?php

namespace app\common\controller;

use app\BaseController;

class BaseAdminController extends BaseController
{
    public array $notNeedLogin = [];

    protected int $adminId = 0;

    protected string $adminToken = '';

    public function initialize()
    {
        // 记录请求开始时间
        request()->requestStartTime = time();
        if (isset($this->request->adminId) && $this->request->adminId !== 0) {
            $this->adminId = $this->request->adminId;
        }
        if (isset($this->request->adminToken) && $this->request->adminToken) {
            $this->adminToken = $this->request->adminToken;
        }
    }

    /**
     * @notes 是否免登录验证
     * @return bool
     * @author 段誉
     * @date 2021/12/27 14:21
     */
    public function isNotNeedLogin(): bool
    {
        $notNeedLogin = $this->notNeedLogin;
        if (empty($notNeedLogin)) {
            return false;
        }
        $action = $this->request->action();

        if (!in_array(trim($action), $notNeedLogin)) {
            return false;
        }
        return true;
    }

    public function convert(array $data, string $className)
    {
        $reflectionClass = new \ReflectionClass($className);
        $instance = $reflectionClass->newInstanceWithoutConstructor();

        foreach ($data as $property => $value) {
            try {
                $propertyReflection = $reflectionClass->getProperty($property);
                $propertyReflection->setAccessible(true); // 设置可访问私有属性
                $propertyReflection->setValue($instance, $value);
            } catch (\ReflectionException $e) {
                // 忽略不存在的属性
                continue;
            }
        }

        return $instance;
    }
}